<template>
	<div>
		<div class="container">
			<h2>{{ info.name }}-{{ info.model }} 历史价格</h2>
			<div class="toolbar">
				<a-form ref="searchRef" layout="inline" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-col :span="4">
						<a-range-picker v-model:value="searchState.date_range" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
					</a-col>
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit">
								<search-outlined />搜索
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="priceSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="189" type="link" @click="editPrice(record)">
									<edit-outlined />修改
								</a-button>
								<a-button v-permission="190" type="link" style="color:#ff7875" @click="deletePrice(record.id)">
									<delete-outlined />删除
								</a-button>
							</a-space>
						</template>
					</template>
				</a-table>
			</div>
		</div>
		<a-modal v-model:visible="visible" :width="400" :title="`${formState.id ? '修改' : '添加'}价格记录`" @ok="savePrice">
			<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '80px' } }}">
				<a-form-item label="价格" name="price" :rules="{required:true, message:'请输入价格'}">
					<a-input v-model:value="formState.price" />
				</a-form-item>
			</a-form>
		</a-modal>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance, onMounted } from "vue";

import dayjs from "dayjs";

import { SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";

import { usePagination } from "vue-request";

const searchRef = ref();
const searchState = reactive({});
const visible = ref(false);
const formState = ref({});
const info = ref({});

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 120,
		align: "left",
		fixed: "left"
	},
	{
		title: "日期",
		dataIndex: "price_date",
		sorter: false,
		width: 300,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "价格",
		dataIndex: "price",
		sorter: false,
		width: 300,
		ellipsis: true
	},
	{
		title: "操作人",
		dataIndex: "user",
		width: 300,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.fullname || text.username;
		}
	},
	{},
	{
		title: "操作时间",
		dataIndex: "update_time",
		width: 180,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));
import { useRoute } from "vue-router";
const route = useRoute();
const { data, loading, run, current, pageSize, total } = usePagination(params => post("price/log", { material_id: route.query.material_id || 0, ...params, ...searchState, date_range: JSON.stringify(searchState.date_range) }), {
	defaultParams: [
		{
			page_size: 30
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

onMounted(() => {
	const material_id = route.query.material_id;
	if (material_id) {
		post("material/info", { id: material_id }).then(data => {
			const { name, model } = data;
			info.value = {
				name,
				model
			};
		});
	}
});

const priceSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);
const editPrice = record => {
	visible.value = true;
	formState.value = { ...record };
};

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };

	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
const formRef = ref();
const { proxy } = getCurrentInstance();
const savePrice = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };
			post("price/save", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;

					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};
const deletePrice = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("price/delete", { id }).then(() => {
				proxy.$message.success("删除成功");
				initData();
			});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>